import React, { PureComponent } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  List,
  Card,
  Radio,
  Input,
  Button,
  Icon,
  Dropdown,
  Menu,
  Avatar,
  Modal,
  Form,
  Upload,
} from 'antd';

import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './MaterialList.less';

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const { Search, TextArea } = Input;
const FormItem = Form.Item;
const { Dragger } = Upload;

const CreateForm = Form.create()(props => {
  const {
    modalVisible,
    fileSelected,
    form,
    handleAdd,
    handleModalVisible,
    handleFileSelect,
  } = props;
  const uploadProps = {
    action: '',
    beforeUpload: () => {
      return false;
    },
    onChange: ({ fileList }) => {
      handleFileSelect(fileList.length);
    },
    listType: 'picture',
  };

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      // form.resetFields();
      handleAdd(fieldsValue);
    });
  };

  const normFile = e => {
    // console.log('Upload event:', e);
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.file;
  };

  const uploadButton = (
    <div>
      <Icon type="plus" />
    </div>
  );

  return (
    <Modal
      title="新建栏目"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <Form layout="vertical">
        <FormItem>
          {form.getFieldDecorator('file', {
            rules: [{ required: true }],
            valuePropName: 'file',
            getValueFromEvent: normFile,
          })(<Dragger {...uploadProps}>{!fileSelected && uploadButton}</Dragger>)}
        </FormItem>
        <FormItem label="标题">
          {form.getFieldDecorator('name', {
            rules: [{ required: false }],
          })(<Input placeholder="请输入" />)}
        </FormItem>
        <FormItem label="描述">
          {form.getFieldDecorator('description', {
            rules: [{ required: false }],
          })(<TextArea rows={2} placeholder="请输入" />)}
        </FormItem>
      </Form>
    </Modal>
  );
});

@connect(({ material, loading }) => ({
  material,
  loading: loading.models.list,
}))
export default class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      fileSelected: false,
    };
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'material/fetch',
    });
  }

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleFileSelect = flag => {
    this.setState({
      fileSelected: !!flag,
    });
  };

  handleAdd = fields => {
    this.props.dispatch({
      type: 'material/add',
      payload: fields,
    });
  };

  handlePaginationChange = (page, pageSize) => {
    const { dispatch } = this.props;
    const params = {
      currentPage: page,
      pageSize,
    };
    dispatch({
      type: 'material/fetch',
      payload: params,
    });
  };

  render() {
    const { material: { data }, loading } = this.props;
    const { modalVisible, fileSelected } = this.state;

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
      handleFileSelect: this.handleFileSelect,
    };

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      pageSize: 10,
      total: data.pagination.total,
      onChange: this.handlePaginationChange,
    };

    const extraContent = (
      <div className={styles.extraContent}>
        <RadioGroup defaultValue="all">
          <RadioButton value="all">全部</RadioButton>
          <RadioButton value="progress">进行中</RadioButton>
          <RadioButton value="waiting">等待中</RadioButton>
        </RadioGroup>
        <Search className={styles.extraContentSearch} placeholder="请输入" onSearch={() => ({})} />
      </div>
    );

    const ListContent = ({ data: { description, createTime } }) => (
      <div className={styles.listContent}>
        <div className={styles.listContentItem}>
          {/* <span>Owner</span> */}
          <p>{description}</p>
        </div>
        <div className={styles.listContentItem}>
          {/* <span>开始时间</span> */}
          <p>{moment(createTime || undefined).format('YYYY-MM-DD HH:mm')}</p>
        </div>
        <div className={styles.listContentItem}>
          <p>205kb</p>
        </div>
      </div>
    );

    const menu = (
      <Menu>
        <Menu.Item>
          <a>编辑</a>
        </Menu.Item>
        <Menu.Item>
          <a>删除</a>
        </Menu.Item>
      </Menu>
    );

    const MoreBtn = () => (
      <Dropdown overlay={menu}>
        <a>
          更多 <Icon type="down" />
        </a>
      </Dropdown>
    );

    return (
      <PageHeaderLayout>
        <div className={styles.standardList}>
          <Card
            className={styles.listCard}
            bordered={false}
            title="标准列表"
            style={{ marginTop: 24 }}
            bodyStyle={{ padding: '0 32px 40px 32px' }}
            extra={extraContent}
          >
            <Button
              type="dashed"
              style={{ width: '100%', marginBottom: 8 }}
              icon="plus"
              onClick={() => this.handleModalVisible(true)}
            >
              添加
            </Button>
            <List
              size="large"
              rowKey="id"
              loading={loading}
              pagination={paginationProps}
              dataSource={data.list}
              renderItem={item => (
                <List.Item actions={[<a>编辑</a>, <MoreBtn />]}>
                  <List.Item.Meta
                    avatar={
                      <Avatar shape="square" size="small">
                        T
                      </Avatar>
                    }
                    title={<a href={item.url}>{item.name}</a>}
                  />
                  <ListContent
                    data={{
                      description: item.description,
                      createTime: item.created_at,
                    }}
                  />
                </List.Item>
              )}
            />
          </Card>
        </div>
        <CreateForm {...parentMethods} modalVisible={modalVisible} fileSelected={fileSelected} />
      </PageHeaderLayout>
    );
  }
}
